package com.schoolhelper.controller.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import android.content.SharedPreferences.Editor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.schoolhelper.model.dao.okhttp.RefactorRequestUrl;
import com.schoolhelper.model.entity.User;
import com.schoolhelper.model.vo.LoginVo;
import com.schoolhelper.model.vo.TokenVo;
import com.schoolhelper.utils.MyCache;
import com.schoolhelper.utils.MySymmetricEncryption;
import com.schoolhelper.utils.constant.Api;

import com.alibaba.fastjson.JSONObject;
import com.schoolhelper.utils.constant.ZyyApi;

import java.util.HashMap;
import java.util.Objects;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    EditText user_id, user_pwd;
    Button btn_login, btn_reg;
    CheckBox checkBox;
    String TAG = "tag:";
    String username;
    String password;
    Boolean is_login;
    SharedPreferences sp;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //https://www.jb51.net/article/85167.htm
        sp = this.getSharedPreferences("local_userinfo", Context.MODE_PRIVATE);
        init();
    }


    public void init() {
        user_id = findViewById(R.id.edit_username);
        user_pwd = findViewById(R.id.edit_pwd);
        btn_login = findViewById(R.id.btn_login);
        btn_reg = findViewById(R.id.btn_register);
        checkBox = findViewById(R.id.checkBox);

        if (sp.getBoolean("checkboxBoolean", false)) {
            user_id.setText(sp.getString("username", null));
            user_pwd.setText(sp.getString("password", null));
            checkBox.setChecked(true);
        }
        btn_login.setOnClickListener(this);
        btn_reg.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        //点击登录按钮
        if (view == btn_login) {
            //获取输入信息
            username = user_id.getText().toString().trim();
            password = user_pwd.getText().toString().trim();

            //判断输入是否为空
            if (username.equals("")) {
                Toast.makeText(LoginActivity.this, "请您输入用户名！", Toast.LENGTH_SHORT).show();
                return;
            } else if (password.equals("")) {
                Toast.makeText(LoginActivity.this, "请您输入密码！", Toast.LENGTH_SHORT).show();
                return;
            }
            is_login = checkBox.isChecked();
            //记住账号密码，下次进入显示
            if (is_login) {
                Editor editor = sp.edit();
                editor.putString("username", username);
                editor.putString("password", password);
                editor.putBoolean("checkboxBoolean", true);
                editor.commit();
            }
            //清空账号密码，下次进入为空
            else {
                Editor editor = sp.edit();
                editor.putString("username", null);
                editor.putString("password", null);
                editor.putBoolean("checkboxBoolean", false);
                editor.commit();
            }
            // encrypt 加密
            password = MySymmetricEncryption.encrypt(password);
            password = MySymmetricEncryption.encrypt(password);
            LoginVo loginVo = new LoginVo(username, password);
            String postResponseJson = RefactorRequestUrl.getPostResponseJson(Api.BASE_URL, ZyyApi.LOGIN_API, new HashMap<>(), loginVo);

            Toast.makeText(LoginActivity.this, postResponseJson, Toast.LENGTH_LONG).show();
            JSONObject responseJson = (JSONObject) JSONObject.parse(postResponseJson);

            if (Objects.equals(responseJson.get("code"), 200)) {
                // 登录环信
                EMClient.getInstance().login(username, password, new EMCallBack() {
                    @Override
                    public void onSuccess() {
                        //登录状态设置
                        MyCache.write(getApplicationContext(), "token", (String) responseJson.get("data"));
                        String token = MyCache.read(getApplicationContext(), "token");
                        //将userId写入内存
                        writeCache(token);
                        //跳转页面
                        Intent intent = new Intent();
                        intent.setClass(LoginActivity.this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }

                    @Override
                    public void onError(int code, String error) {
                        runOnUiThread(() -> {
                            Toast.makeText(LoginActivity.this, "登录失败： " + code + ": " + error, Toast.LENGTH_SHORT).show();
                        });
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }
                });
            }
        }

        //点击注册按钮
        else if (view == btn_reg) {
            Intent intent = new Intent();
            intent.setClass(LoginActivity.this, RegisterActivity.class);
            Toast.makeText(getApplicationContext(), "注册", Toast.LENGTH_LONG).show();
            startActivity(intent);
        }

    }

    public void writeCache(String token) {
        TokenVo tokenVo = new TokenVo(token);
        String jsonStr = RefactorRequestUrl.getPostResponseJson
                (Api.BASE_URL, ZyyApi.GET_LOG_STATE_API, new HashMap<>(), tokenVo);
        JSONObject responseJson = (JSONObject) JSONObject.parse(jsonStr);
        if (Objects.equals(responseJson.get("code"), 200)) {
            JSONObject dataJson = (JSONObject) responseJson.get("data");
            User user = JSON.parseObject(String.valueOf(dataJson), User.class);
            MyCache.write(getApplicationContext(), "userId", user.getUserId().toString());
            String json = JSON.toJSONString(user, SerializerFeature.WriteMapNullValue);
            MyCache.write(getApplicationContext(), "userInfo", json);

        }
    }
}